<template>
  <div id="SkillFollowRead">
    <crumb />
    <el-table border :data="tableData.subjectList" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
      <el-table-column align="center" prop="resource_role_name" label="角色" width="120"></el-table-column>
      <el-table-column align="center" prop="resource_oral_content" label="对话内容"></el-table-column>
      <el-table-column align="center" prop="file_url" label="原音" width="80">
        <template slot-scope="scope">
          <i class="el-icon-video-pause" @click='AudioPause("audio" + scope.$index,scope.$index)' v-if="scope.row.isPlayOk"></i>
          <i class="el-icon-video-play" @click='AudioPlay("audio" + scope.$index,scope.$index)' v-if="!scope.row.isPlayOk"></i>

          <audio :src="scope.row.file_url" :ref='"audio"+scope.$index' v-show="false"></audio>
          <!-- {{row.file_url}}  -->
        </template>
      </el-table-column>
      <el-table-column align="center" label="录音">
        <template>
          <i class="el-icon-mic" @click='SoundPlay'></i>
          <!-- <el-button @click="startRecording">开始</el-button> -->
          <!-- <el-button @click="stopRecording">停止</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="isSound?'已经连接麦克风':'请先连接到麦克风'"
      :visible.sync="dialogVisible"
      width="30%"
      center
      :close-on-press-escape='false'
      :close-on-click-modal='false'
      @close='Resetting'
      >
      <div style="text-align:center;">
        <span v-if="!isSound">并检测到麦克风已连接</span>
        <span v-if="isSound"><i class="el-icon-mic"></i></span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!isSound" @click="retrySound">重试</el-button>
        <el-button type="primary" v-if="isSound&&!isStart" @click="startRecording">开始</el-button>
        <div>
          <el-button type="primary" v-if="isStart" @click="Resetting">重录</el-button>
          <el-button type="danger"  v-if="isStart" @click="stopRecording">提交</el-button>
        </div>
        <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { speechMain, speechStart, speechSubmit, speechUpdateDuration } from '@/api/student/training/speech'
import Recorder from 'recorder-js'
const audioContext = new (window.AudioContext || window.webkiAudioContext)()
const recorder = new Recorder(audioContext, {
  // onAnalysed: data => console.log(data)
})
// eslint-disable-next-line no-unused-vars
let isRecording = false
// eslint-disable-next-line no-unused-vars
let blobDow = null
// let isOkSound = false
// 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
// 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。

//   navigator.mediaDevices.getUserMedia = function (constraints) {
//     // 首先，如果有getUserMedia的话，就获得它
//     var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia
//     // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
//     if (!getUserMedia) {
//       return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
//     }
//     // 否则，为老的navigator.getUserMedia方法包裹一个Promise
//     return new Promise(function (resolve, reject) {
//       getUserMedia.call(navigator, constraints, resolve, reject)
//     })
//   }
// }
navigator.mediaDevices.getUserMedia({ audio: true })
  .then(stream => recorder.init(stream))
  .catch(err => { console.log('Uh oh... unable to get stream...麦克风未连接', err) })

// eslint-disable-next-line no-unused-vars
function download () {
  Recorder.download(blobDow, 'my-audio-file')
}

export default {
  name: 'SkillFollowRead',
  components: {},
  data () {
    return {
      dialogVisible: false,
      isSound: false,
      isStart: false,
      isRecording: false,
      blob: null,
      tableData: [],
      setTimeFn: null
    }
  },
  mounted () {
    this.speechStart()
    this.speechUpdateDuration()
  },
  methods: {
    async speechStart () {
      // main方法暂时没用用到
      await speechMain({
        'lessonOralCatalogId': this.$route.query.lessonOralCatalogId,
        'resourceOralId': this.$route.query.resourceOralId
      })
      const resOne = await speechStart({
        'lessonOralCatalogId': this.$route.query.lessonOralCatalogId,
        // 'lessonOralCatalogId': this.$route.query.resource_oral_id,
        'resourceOralId': this.$route.query.resourceOralId,
        // 'resourceOralId': this.$route.query.resource_oral_id,
        'oralNum': this.$route.query.oralNum,
        'lessonOralBatchId': this.$route.query.lessonOralBatchId
      })
      this.tableData = resOne.data
    },
    AudioPlay (ref, index) {
      for (const key in this.$refs) {
        if (ref === key) {
          this.$refs[key].play()
          this.$set(this.tableData.subjectList[index], 'isPlayOk', true)
          // this.tableData[index].isPlayOk = true
        } else {
          this.tableData.subjectList.forEach((item, indexOne) => {
            if (index !== indexOne) {
              this.$set(this.tableData.subjectList[indexOne], 'isPlayOk', false)
            };
          })
          this.$refs[key].currentTime = 0
          this.$refs[key].pause()
          // this.$set(this.tableData[index], 'isPlayOk', false)
        }
        this.$refs[key].addEventListener('ended', this.PlayOk(event, key, index), false)
      }
    },
    PlayOk (eventTar, key, index) {
      return (eventAudio) => {
        this.tableData.subjectList[index].isPlayOk = false
      }
    },
    AudioPause (ref, index) {
      this.$refs[ref].pause()
      this.tableData.subjectList[index].isPlayOk = false
    },
    SoundPlay () {
      // 临时使用结束之后放开
      this.retrySound()
      this.dialogVisible = true
      // console.log(this.isSound)
      // 临时使用
      // setTimeout(() => {
      //   this.isSound = true
      // }, 1000)
    },
    retrySound () {
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => { recorder.init(stream); this.isSound = true })
        .catch(err => { console.log('Uh oh... unable to get stream...麦克风未连接', err); this.isSound = false })
    },
    Submit () {},
    Resetting () {
      this.isStart = false
      recorder.stop()
    },
    startRecording () {
      recorder.start()
        .then(() => { isRecording = true; console.log('开始了'); this.isStart = true })
    },
    stopRecording () {
      recorder.stop()
      speechSubmit({
        lessonOralBatchId: this.tableData.lessonOralBatchId,
        resultJson: '',
        score: '90'
      }).then(res => {
        // console.log(res)
        this.$router.push({ name: 'skillfollowreport',
          query: {
            'lessonOralBatchId': this.tableData.lessonOralBatchId,
            'lessonOralCatalogId': this.$route.query.lessonOralCatalogId,
            'resourceOralId': this.$route.query.resourceOralId
          } })
      })
      // recorder.stop()
      //   .then(({ blob, buffer }) => {
      //     console.log(blob, buffer)
      //     // eslint-disable-next-line no-self-assign
      //     blobDow = blob
      //     download()
      //     // buffer is an AudioBuffer
      //   })
    },
    async speechUpdateDuration () {
      await speechUpdateDuration({
        lessonOralBatchId: this.$route.query.lessonOralBatchId
      })
      this.setTimeFn = setTimeout(this.speechUpdateDuration, 8000)
    }
  },
  destroyed () {
    clearTimeout(this.setTimeFn)
  }
}
</script>

<style scoped lang="scss" >
.el-dialog{
 .el-dialog__body{
    text-align:center !important;
  }
}
</style>
